package com.hitqz.robot.camera.callback;

import com.hitqz.robot.camera.dto.AreaTemplateDTO;
import com.hitqz.robot.camera.service.HCNetSDK;
import com.hitqz.robot.camera.entity.ConstantsFace;
import com.sun.jna.Pointer;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;


@Slf4j
public class HkTemperatureCallBack implements HCNetSDK.FRemoteConfigCallBack {

    private static final DecimalFormat df = new DecimalFormat("0.00");

    @Override
    public void invoke(int dwType, Pointer lpBuffer, int dwBufLen, Pointer pUserData) {
        try {
            log.debug("[HK][TemperatureCallBack] dwType:" + dwType);
            if (dwType == HCNetSDK.NET_SDK_CALLBACK_TYPE.NET_SDK_CALLBACK_TYPE_DATA.getValue()) {
                HCNetSDK.NET_DVR_THERMOMETRY_UPLOAD lpThermometry = ConstantsFace.HK_THERMOMETRY_UPLOAD;
                lpThermometry.dwSize = lpThermometry.size();
                lpThermometry.write();
                Pointer ptemp = lpThermometry.getPointer();
                byte[] bufferData = lpBuffer.getByteArray(0, lpThermometry.size());
                ptemp.write(0, bufferData, 0, bufferData.length);
                lpThermometry.read();
                int ruleID = lpThermometry.byRuleID;
                String name = null;
                name = new String(lpThermometry.szRuleName, StandardCharsets.UTF_8).trim().split("\0")[0];
                String ip = pUserData.getString(0);
                if (lpThermometry.struLinePolygonThermCfg != null) {
                    String max = df.format(lpThermometry.struLinePolygonThermCfg.fMaxTemperature);
                    String min = df.format(lpThermometry.struLinePolygonThermCfg.fMinTemperature);
                    String aver = df.format(lpThermometry.struLinePolygonThermCfg.fAverageTemperature);
                    ConstantsFace.TEMPERATURE_TABLE.put(ip, ruleID, new AreaTemplateDTO(Integer.valueOf(name), ruleID, Float.parseFloat(max), Float.parseFloat(min), Float.parseFloat(aver)));
                    log.info("[HK][TemperatureCallBack]ip:{},name:{},ruleId:{},temperature: max:{}, min:{} aver:{}", ip, name, ruleID, max, min, aver);
                } else {
                    log.warn("[HK][TemperatureCallBack] LinePolygonThermCfg is null");
                }
                //lpThermometry.clear();
            }
        }catch (Exception e){
            log.error("[HK][TemperatureCallBack] error {}",e.getMessage());
        }
    }

}

